package cn.wolfcode.mq;

import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author LuoRis
 * @date 2021/03/08 10:48
 * @description 消费MQ信息
 */
@Component
@RocketMQMessageListener(
        topic = MQConstant.ORDER_PEDDING_TOPIC,
        consumerGroup = "MqOrderInfoListener"
)
@Slf4j
public class MqOrderInfoListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private ISeckillProductService seckillProductService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;



    @Override
    public void onMessage(OrderMessage orderMessage) {
        log.info("----------进入订单队列-----------");
        //消息的标签
        OrderMQResult orderMQResult = new OrderMQResult();
        String tag = "";
        Long seckillId = orderMessage.getSeckillId();
        Integer time = orderMessage.getTime();
        String token = orderMessage.getToken();
        Long userPhone = orderMessage.getUserPhone();

        orderMQResult.setTime(time);
        orderMQResult.setToken(token);
        orderMQResult.setSeckillId(seckillId);

        try {
            //int i  = 1/0;
            OrderInfo orderInfo = seckillProductService.doSeckill(time, seckillId, userPhone);
            tag=MQConstant.ORDER_RESULT_SUCCESS_TAG;
            orderMQResult.setOrderNo(orderInfo.getOrderNo());
            //发送延时信息
            //这个 MessageBuilder.withPayload(orderMQResult).build() 不知道是干嘛的
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, MessageBuilder.withPayload(orderMQResult).build(),5000,17);
        }catch (Exception e){
            tag=MQConstant.ORDER_RESULT_FAIL_TAG;
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
        }

        rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC+":"+tag,orderMQResult);
    }



}
